/*
 * Memory.java
 * 
 * This file is part of Netuno Psamata.
 * 
 * CajuScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3, or (at your option) 
 * any later version.
 * 
 * CajuScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CajuScript.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.netuno.psamata;

/**
 * Memory.
 * @author eduveks
 */
public final class Memory {
    /**
     * Memory.
     */
    private Memory() { }
    /**
     * Last execution of Garbage Collect.
     */
    private static long gcLast;
    /**
     * Garbage Collect Delay.
     */
    private static int gcDelay = 50;
    /**
     * Max Garbage Collect Execute.
     */
    private static int gcMax = 8;
    /**
     * Get Memory Used.
     * @return Used Memory in MB
     */
    public static long getMemoryUsed() {
        collectGarbage();
        Runtime rt = Runtime.getRuntime();
        return (int) ((rt.totalMemory() - rt.freeMemory()) / 1024 / 1024);
    }
    /**
     * Get Memory Free.
     * @return Free Memory in MB
     */
    public static int getMemoryFree() {
        collectGarbage();
        Runtime rt = Runtime.getRuntime();
        return (int) (rt.freeMemory() / 1024 / 1024);
    }
    /**
     * Get Memory Max.
     * @return Max Memory in MB
     */
    public static int getMemoryMax() {
        collectGarbage();
        Runtime rt = Runtime.getRuntime();
        return (int) (rt.maxMemory() / 1024 / 1024);
    }
    /**
     * Execute Garbage Collect.
     */
    public static synchronized void collectGarbage() {
        Runtime runtime = Runtime.getRuntime();
        long total = runtime.totalMemory();
        long time = System.currentTimeMillis();
        if (gcLast + gcDelay < time) {
            for (int i = 0; i < gcMax; i++) {
                runtime.gc();
                long now = runtime.totalMemory();
                if (now == total) {
                    gcLast = System.currentTimeMillis();
                    break;
                }
                total = now;
            }
        }
    }

}
